package by.kniazhych.core.server.local.logic {
	
	/**
	 * ...
	 * @author Boutylin Mikhail
	 */
	
	import by.kniazhych.core.constants.PeaceType;
	import by.kniazhych.core.data.game.PeacePosition;
	import by.kniazhych.core.server.local.data.MotionCommand;
	import by.kniazhych.core.server.local.logic.peaces.AbstractPeace;
	import by.kniazhych.core.server.local.data.BoardData;
	import by.kniazhych.core.server.local.logic.peaces.PeaceLogicFactory;
	import flash.events.EventDispatcher;
	
	public class LogicController extends EventDispatcher{
		
		private var _factory:PeaceLogicFactory;
		protected var _data:BoardData;
		
		public function LogicController(data:BoardData) {
			super(this);
			_data = data;
			_factory = new PeaceLogicFactory(this);
		}
		
		//--------------------------------------------------------------------------
		//
		//  PUBLIC METHODS
		//
		//--------------------------------------------------------------------------
		
		/**
		 * controls if the motion is valid, and executes it
		 * @param	sP the star motion position
		 * @param	fP the last motion position
		 * @return motion validation
		 */
		
		public function processMotion(sP:PeacePosition, fP:PeacePosition, test:Boolean = false):Boolean {
			
			
			var approved:Boolean = _controlMotionRules(sP, fP);
			
			
			if (approved) {
				_data.test(new MotionCommand(sP, fP));
				//control if the palyer is under check
				if (_data.currentPlayer.isUnderCheck) {
					approved = false;
					_data.rollBack();
				}else {
					if (test) {
						_data.rollBack();
					}else {
						_data.executeMotion(sP, fP);
					}
				}
			}
			return approved;
		}
		
		public function executeMotion(sP:PeacePosition, fP:PeacePosition):void {
			_data.executeMotion(sP, fP);
		}
		
		public function getPeaceLogicByCell(p:PeacePosition):AbstractPeace {
			return _factory.getPeace(_data.getCellState(p));
		}
		
		public function get data():BoardData { return _data; }
		
		//--------------------------------------------------------------------------
		//
		//  PROTECTED METHODS
		//
		//--------------------------------------------------------------------------
		
		/**
		 * 
		 * @param	sP
		 * @param	fP
		 * @return posibiliy to ecxecute motion independely of board position
		 */
		
		protected function _controlMotionRules(sP:PeacePosition, fP:PeacePosition, test:Boolean = false):Boolean {
			//save start cell
			var oldCellState:uint = _data.getCellState(sP);
			//start cell can't be empty
			
			if (oldCellState == PeaceType.BLANK_CELL) return false;
			
			var peace:AbstractPeace = _factory.getPeace(oldCellState);
			
			//control if peace can do this motion
			if (!peace.checkMotion(sP, fP)) return false;
			//control if peace is not illegaly on the tron
			if(!test) if (!(peace.isNobel() || (fP.x != 4 || fP.y != 4))) return false;
			
			return true;
		}
		
	}

}